﻿/*
 * empfänger.c
 *
 * Created: 12.10.2011 22:51:11
 *  Author: Alex
 */ 

#include "main.h"

volatile uint8_t intCount = 0;

int main(void)
{
	//int0_init();
	
    /* initialize display, cursor oon */
    lcd_init(LCD_DISP_ON_CURSOR_BLINK);
	lcd_clrscr();
    lcd_puts("****** RFM-Empfang-Test ******");		// Text in einzelnen Zeichen ausgeben
	
	for(int x=0;x<4;x++)
	{
		lcd_command(LCD_MOVE_DISP_LEFT);
		_delay_ms(200);
	}
	rf12_init();				// ein paar Register setzen (z.B. CLK auf 10MHz)
	rf12_setfreq(RF12FREQ(433.92));		// Sende/Empfangsfrequenz auf 433,92MHz einstellen
	rf12_setbandwidth(4, 1, 4);		// 200kHz Bandbreite, -6dB Verstärkung, DRSSI threshold: -79dBm 
	rf12_setbaud(19200);			// 19200 baud
	rf12_setpower(0, 6);			// 1mW Ausgangangsleistung, 120kHz Frequenzshift
	for(int x=0;x<4;x++)
	{
		lcd_command(LCD_MOVE_DISP_RIGHT);
		_delay_ms(200);
	}

	
	//timer0_init();
	
	DDRD = 0x01;    // PD0 -> Ausgang (LED grün)

	sei();

	// Init RFM
	lcd_puts("RFM12 init");
	//myrfm12_setup();
	
	//_delay_ms(1000);	

	lcd_gotoxy(0,1);
	//lcd_string("          ");

//	uint8_t count = 0;
	unsigned char rxdata_T[] = "Funktionstest";
	unsigned char rxdata[20] = {0};
	uint8_t olddata[23] = {0};
	lcd_puts((char*) rxdata_T);
	_delay_ms(200);
	lcd_gotoxy( 0, 1 );
	lcd_puts("                  ");
	uint8_t oldX, newX;
	uint8_t length = 0;
	char BUFFER[10];
	while(1)
	{
		unsigned char ret;
		unsigned char test[50];
/* none blocking sample */	
		unsigned char test2[50];
		
		sprintf(test, "Start val: %u ", rf12_rxstart());
		//UART_Tx_Str(test, sprintf(test, "Start val: %u\n", rf12_rxstart()));
		lcd_gotoxy(0,0);
		lcd_puts(test);
		ret = 255;				//not completed yet
		while(ret == 255)
		{
			ret = rf12_rxfinish(test2);	//try if transfer completed
		}
		switch(ret)
		{
			case 0: lcd_gotoxy(0,1);
					lcd_puts("ERROR CRC");
					break;
			case 253: lcd_gotoxy(0,1);
					lcd_puts("No at me addressed");
					break;
		}
		sprintf(test, " ret: %i ", ret);
		lcd_gotoxy(13,0);
		lcd_puts(test);
		
		//UART_Tx_Str(test, sprintf(test, "ret: %u\n", ret));
		if(ret != 0 && ret != 254 && ret != 253)				//no CRC error && no old str && no at me addr
		{	lcd_gotoxy(0,1);
			lcd_puts(test2);
		}		
	}
    return 0;
}

void timer0_init()
{
	TCCR0 = (1<<CS02)|(1<<CS00);		// Prescale = CLK/1024
	TIMSK |= (1<<TOIE0);	// Interrupt Overflow
}

volatile uint8_t i=0;

ISR (TIMER0_OVF_vect)
{
	//LED-Toggeln
	i++;
	if(i>50)
	{
		//PORTD ^= (1<<PD0);
		i=0;
	}
}

void int0_init()
{
	MCUCR = (0<<ISC00) | (1<<ISC01);	// rising edge
	GICR |= (1<<INT0);					// enable
}

/*ISR (INT0_vect)
{
	PORTD ^= (1<<PD0);	// LED toggeln
	//_delay_ms(44);
	intCount++;
//	myrfm12_rxdata(rxdata,17);
//	lcd_gotoxy( 0, 1 );
//	lcd_puts((char*)rxdata);
}*/